﻿Shader "Custom/PixelBlurMask" 
{
	Properties 
	{
		_MainTex ("Base (RGB)", 2D) = "white" {}
	}
	
	SubShader 
	{

		Pass
		{
			Tags
			{
				"LightMode" = "Always"
			}
			ZTest Always Cull Off ZWrite Off Fog { Mode off }

			CGPROGRAM
			#pragma exclude_renderers xbox360 ps3 flash
			#pragma vertex	vert
			#pragma fragment frag
			#pragma fragmentoption ARB_precision_hint_fastest

			#include "UnityCG.cginc"

			uniform sampler2D		_MainTex;
			uniform sampler2D		_GlobalBlurBufferTexture;
			uniform float4			_MainTex_TexelSize;
			uniform float			_BlurStrength;


			v2f_img vert( appdata_img v )
			{
				v2f_img		o;
				o.pos = mul( UNITY_MATRIX_MVP, v.vertex );

#ifdef UNITY_HALF_TEXEL_OFFSET
				v.texcoord.y += _MainTex_TexelSize.y;
#endif

				o.uv = MultiplyUV( UNITY_MATRIX_TEXTURE0, v.texcoord );
				return o;
			}


			fixed4 frag( v2f_img i ) : COLOR
			{
				fixed4 main_col = tex2D( _MainTex, i.uv );
				fixed3 blur = tex2D( _MainTex, i.uv ).rgb * 0.199471;
				fixed mask = tex2D( _GlobalBlurBufferTexture, i.uv ).r;

				blur.rgb += tex2D( _MainTex, i.uv + _MainTex_TexelSize.xy * _BlurStrength * 1 ).rgb;
				blur.rgb += tex2D( _MainTex, i.uv + _MainTex_TexelSize.xy * _BlurStrength * 2 ).rgb;
				blur.rgb += tex2D( _MainTex, i.uv + _MainTex_TexelSize.xy * _BlurStrength * 3 ).rgb;
				blur.rgb += tex2D( _MainTex, i.uv + _MainTex_TexelSize.xy * _BlurStrength * 4 ).rgb;

				blur.rgb += tex2D( _MainTex, i.uv - _MainTex_TexelSize.xy * _BlurStrength * 1 ).rgb;
				blur.rgb += tex2D( _MainTex, i.uv - _MainTex_TexelSize.xy * _BlurStrength * 2 ).rgb;
				blur.rgb += tex2D( _MainTex, i.uv - _MainTex_TexelSize.xy * _BlurStrength * 3 ).rgb;
				blur.rgb += tex2D( _MainTex, i.uv - _MainTex_TexelSize.xy * _BlurStrength * 4 ).rgb;

				blur.rgb /= 8;
				fixed3 result = lerp( main_col.rgb, blur.rgb, mask );
				return fixed4( result, main_col.a );				
			}
			ENDCG
		}
	}
	Fallback off
}
